<?php
class UsersController extends AppController {

	var $name = 'Users';
	var $helpers = array('Html','Form','Ajax','Javascript');
	

	function index() {
		$this->User->recursive = 0;
		$this->set('users', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid User.', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->set('user', $this->User->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->User->create();
			if ($this->User->save($this->data)) {
				$this->Session->setFlash(__('The User has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
			}
		}
		$groups = $this->User->Group->find('list');
		$this->set(compact('groups'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid User', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->User->save($this->data)) {
				$this->Session->setFlash(__('The User has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->User->read(null, $id);
		}
		$groups = $this->User->Group->find('list');
		$this->set(compact('groups'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for User', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->User->del($id)) {
			$this->Session->setFlash(__('User deleted', true));
			$this->redirect(array('action'=>'index'));
		}
	}
	
	function login() {
		
		if($this ->Session->read("user_id")>0)
		{
				$this->redirect(Router::url("/", true).'projects/user_projects');		
		}
		
		$this->set('authentication_error_message',"");
		
		if(isset($_POST['username']))
		{
		
			$password=$this->User->field('password', array('username' => ''.$_POST['username']));
			
			if($_POST['username']=="" || $_POST['password']=="")
			{
				$this->set('authentication_error_message',"Username/Password should not be blank.");
			}
			else if($password==md5($_POST['password']))
			{
				$user_id=$this->User->field('id', array('username' => ''.$_POST['username']));
				$_SESSION['user_id']=$user_id;
				
			
				$this->redirect(Router::url("/", true).'projects/user_projects');
			}
			else
			{
				$this->set('authentication_error_message',"<font color='red'>Username and/or Password mismatched. Please try again...</font>");
			}
		}
		
		
		

	}
	
	function logout()
	{  
	     session_destroy();
	  	 $this->redirect("/users/login");  
	}  
	

}
?>